//
//  SetPwdViewModel.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/5/18.
//

import Combine

final class SetPwdViewModel: ObservableObject {
     
    var account: String?
    @Published var password1: String = ""
    @Published var password2: String = ""
    @Published var toastMsg: String?
    @Published var isLoading: Bool = false
    @Published var isPasswordHidden: Bool = true
    
    @Published var executeSucces: Bool = false
    
    var cancellables = Set<AnyCancellable>()
    
    var isRegister: Bool = false
    
    init(account: String, isRegister: Bool) {
        self.account = account
        self.isRegister = isRegister
    }
    
    func verifyPwd() -> Bool    {
        
        if (password1.isEmpty || password2.isEmpty)
        {
            return false
        }
//        if(password1 != password2)
//        {
//            return false
//        }
        if !isValidPassword(password1)
        {
            // 8到20个字符包含字母和数字 展示
            return false
        }
        return true
    }
    
    func execute()
    {
        if isRegister {
            register()
        }
        else {
            resetPwd()
        }
    }
    
    private  func register()
    {
        guard let account = account else {
            print("注册时，account为空")
            return
        }
        
        var grantType: LoginGrantType = .email
        if account.isPhoneNum
        {
            grantType = .sms
        }
        
        if(password1 != password2)
        {
            toastMsg = "两次密码不一致"
            return
        }
        
        self.executeSucces = false
        UIApplication.shared.hideKeyboard()
        self.isLoading = true
        CDRegisterStep().execute(.init(userName: account, password: password1, grantType: grantType))
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: {[weak self] completion in
                switch completion {
                case .finished:
                    print("119615, 注册 finished")
                    self?.isLoading = false
                case .failure(let error):
                    print("119615, 注册 error: \(error)")
                    self?.isLoading = false
                    self?.toastMsg = error.localizedDescription
                }
            }, receiveValue: {[weak self] userInfo in
                print("119615,注册 value: \(userInfo)")
                self?.isLoading = false
                self?.executeSucces = true
              
            })
            .store(in: &cancellables)
    }
    
    private func resetPwd()
    {
        guard let account = account else {
            print("修改时，account为空")
            return
        }
        if(password1 != password2)
        {
            toastMsg = "两次密码不一致"
            return
        }
        
        self.executeSucces = false
        UIApplication.shared.hideKeyboard()
        self.isLoading = true
        CDResetPwdStep().execute(.init(userName: account, password: password1))
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: {[weak self] completion in
                switch completion {
                case .finished:
                    print("119615, 修改密码 finished")
                    self?.isLoading = false
                case .failure(let error):
                    print("119615, 修改密码 error: \(error)")
                    self?.isLoading = false
                    self?.toastMsg = error.localizedDescription
                }
            }, receiveValue: {[weak self] userInfo in
                print("119615, 修改密码 value: \(userInfo)")
                self?.isLoading = false
                self?.executeSucces = true
              
            })
            .store(in: &cancellables)
    }
    
    
    
    private func isValidPassword(_ password: String) -> Bool {
        let pattern = #"^(?=.{8,})((?=.*[a-zA-Z])(?=.*\d)|(?=.*\d)(?=.*[@$!%*?&])|(?=.*[a-zA-Z])(?=.*[@$!%*?&])|(?=.*[a-zA-Z])(?=.*\d)(?=.*[@$!%*?&]))[a-zA-Z\d@$!%*?&]+$"#

        let regex = try? NSRegularExpression(pattern: pattern)
        let range = NSRange(location: 0, length: password.utf16.count)
        return regex?.firstMatch(in: password, options: [], range: range) != nil
    }

}
